package cn.fl.finance.controller;

import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.vo.AssParkingValidVO;
import cn.fl.finance.condition.FinPayApplyInfoQC;
import cn.fl.finance.constant.FinFlowModelConstant;
import cn.fl.finance.constant.FinPayApplyInfoConstant;
import cn.fl.finance.dto.FinPayApplyInfoDTO;
import cn.fl.finance.service.IFinPayApplyInfoService;
import cn.fl.finance.util.BaseResultVO;
import cn.fl.finance.util.FlowStartParmsVO;
import cn.fl.finance.vo.FinPayApplyInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.system.vo.SysUsrVO;
import fl.ass.facade.constant.AssFileConstant;
import fl.carloan.facade.carloan.constant.OdrBscInfoConstant;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.condition.SysFlowManageVQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.SysFlowManageVDTO;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description: 付款申请信息表 控制层
 */
@Controller
@RequestMapping("/finance/finPayApplyInfo")
public class FinPayApplyInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FinPayApplyInfoController.class);

	/**
	 * FinPayApplyInfo 服务层BEAN
	 */
	@Autowired
	private IFinPayApplyInfoService finPayApplyInfoService;
	
	@Autowired
	private IFlowApiService flowApiService;
	
	/**
	 * SysUlFilesRec 服务层BEAN
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	/**
	 *ISysUsrService 服务层BEAN
	 */
	@Autowired
	private ISysUsrService sysUsrService;
	
	
	/**
	 * 初始化列表
	 */
	@RequestMapping(value = "/addFlowStart.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) {
		BaseResultVO result = new   BaseResultVO("操作成功");
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			result.setInfo("操作失败");
			result.setError("id不能为空");
			return result;
		}
		//查询流程最新版本
		SysFlowManageVQueryCondition flowManaQC = new SysFlowManageVQueryCondition();
		flowManaQC.setSysCd(OdrBscInfoConstant.SYS_CD);
		flowManaQC.setIsDel(BaseConstant.IS_YESNO_NO);
		flowManaQC.setIsValid(BaseConstant.IS_YESNO_YES);
		flowManaQC.setModelTyp(FinFlowModelConstant.FLOW_MODEL_LOAN);
		//flowManaQC.setOrgCd(odrBscInfoDTO.getCstMgrOrgCd());
		flowManaQC.setProcDefKey(FinFlowModelConstant.FLOW_LOAN_PRE_ID);
		List<SysFlowManageVDTO> flowManageVListForStart = this.flowApiService.searchFlowManageVListForStart(flowManaQC);
		if(CollectionUtils.isEmpty(flowManageVListForStart)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("未查询到可用的流程版本.");
			BaseLogUtils.info(logger, "addFlowStart", "=flowManaQC : "+JSON.toJSONString(flowManaQC)+"=flowManageVListForStart : "+JSON.toJSONString(flowManageVListForStart), CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SysFlowManageVDTO sysFlowManageVDTO = flowManageVListForStart.get(0);
		
		
		
		FlowStartParmsVO vo = new FlowStartParmsVO();
		vo.setId(id);
		vo.setProcDefId(sysFlowManageVDTO.getProcDefId());
		vo.setProcDefKey(sysFlowManageVDTO.getProcDefKey());
		vo.setProcNo(sysFlowManageVDTO.getProcNo());
		
		//接口调用 dto字段 code 200 标识交互成功
		DataResultDTO dto = finPayApplyInfoService.addFlowStart(vo);
		if(!dto.getCode().equals("200")){
			result.setInfo("操作失败");
			result.setError(dto.getInfo());
		}
		return result;
	}


	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("finance/finPayApplyInfo/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("finance/finPayApplyInfo/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FinPayApplyInfoQC qc = new FinPayApplyInfoQC();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.finPayApplyInfoService.searchListPage(page);
		List<FinPayApplyInfoVO> list = (List<FinPayApplyInfoVO>) pager.getResultList();
		ListPageVO<FinPayApplyInfoVO> listPage = new ListPageVO<FinPayApplyInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.finPayApplyInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FinPayApplyInfoVO vo = this.finPayApplyInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		FinPayApplyInfoVO entity = null;
		try {
			entity = new FinPayApplyInfoVO();
			//TODO ADD PARAM
			Long id = this.finPayApplyInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FinPayApplyInfoVO entity = null;
		try {
			entity = new FinPayApplyInfoVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.finPayApplyInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 跳转城配流程附加信息页面
	 */
	@RequestMapping(value = "/toLoanInfoPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAdditionalInfoList(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");//业务主键
		
		String isMust = request.getParameter("isMust");//0表示全部可以编辑 1表示全部不可编辑 全部是相对的
		String isAccount = request.getParameter("isAccount");//0表示帐号可以编辑 1表示帐号不可以编辑
		//TODO
		ModelAndView view = new ModelAndView("");
		view.addObject("id", id);
		
		if(StringUtils.isNotEmpty(isMust)){
			view.addObject("isMust", isMust);
		}
		if(StringUtils.isNotEmpty(isAccount)){
			view.addObject("isAccount", isAccount);
		}
		return view;
	}

	/**
	 * 根据借款记录ID获取付款申请list
	 */
	@RequestMapping(value = "/selectList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object selectList(HttpServletRequest request, HttpServletResponse response) {
		ListPageVO<FinPayApplyInfoDTO> res = null;
		List<FinPayApplyInfoDTO> finPayApplyInfoDTOS = null;
		try {
			String loanId = request.getParameter("loanId");//借款记录ID
			String flowNo = request.getParameter("flowNo");//流程编号

			FinPayApplyInfoQC qc = new FinPayApplyInfoQC();
			if(StringUtils.isNotEmpty(loanId)){
				qc.setLoanId(Long.valueOf(loanId));
			}
			if(StringUtils.isNotEmpty(flowNo)){
				qc.setPNo(flowNo);
			}
			qc.setIsDel("0");
			finPayApplyInfoDTOS = this.finPayApplyInfoService.selectList(qc);
			res= new ListPageVO<>(finPayApplyInfoDTOS,finPayApplyInfoDTOS.size());
		}catch (Exception ex) {
				BaseLogUtils.error(logger, "initList", "付款申请查询数据失败：" + ex.getMessage(), CurrentThreadContext.getCurrentUserName(),ex);
		}
		return res;
	}
	
	/**
	 * 初始化文件列表
	 */
	@RequestMapping(value = "/initFilesList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initFilesList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String pkId = request.getParameter("pkId");
		String tabNm = request.getParameter("tabNm");
		String pkIdList = request.getParameter("pkIdList");//主键List
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
		if ((StringUtils.isEmpty(pkId) && StringUtils.isEmpty(pkIdList))||StringUtils.isEmpty(tabNm)) {
			return page;
		}
		//判断此次传参是否为主键List
		if (StringUtils.isNotEmpty(pkIdList)) {
			pkIdList = pkIdList.substring(1, pkIdList.length()-1);
		    String[] arr = pkIdList.split(", ");
		    List<String> pkList = java.util.Arrays.asList(arr);
			qc.setPkIdList(pkList);
		}else{
			qc.setPkId(pkId);
		}
		
		qc.setCfgCd(FinPayApplyInfoConstant.FIN_PAY_APPLY_INFO_CFGCD);//ASS001-拖车模块
		qc.setCfgDtlCd(FinPayApplyInfoConstant.FIN_PAY_APPLY_INFO_CFGDTLCD_1);
		qc.setTabNm(tabNm);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码-必须条件
		page.setCondition(qc);
		
		List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(qc);
		
		//遍历list查询文件上传者-真实姓名
		SysUsrVO usrVo = null;
		String sysCd = CurrentThreadContext.getCurrentSysCd();
		if(CollectionUtils.isNotEmpty(list) && list.size()>0){
			for(SysUlFilesRecVO vo : list){
				usrVo = this.sysUsrService.selectById(vo.getCrtUsrId(), sysCd);
				vo.setCrtUsrRlNm(usrVo.getRefRlNm());
			}
		}
		page.setResultList(list);
		page.setTotalCount(list.size());
		
		ListPageVO<SysUlFilesRecVO> listPage = new ListPageVO<SysUlFilesRecVO>(list, list.size());
		return listPage;
	}
}

